// pages/orders/orders.js
const { apiService } = require('../../utils/api')
const { showSuccess, showError, formatPrice } = require('../../utils/util')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    orders: [],
    loading: false,
    hasMore: true,
    pageNum: 1,
    pageSize: 10,
    currentTab: 'all', // all, pending, paid, delivered, completed, cancelled
    statusOptions: [
      { key: 'all', label: '全部' },
      { key: 'pending', label: '待支付' },
      { key: 'paid', label: '已支付' },
      { key: 'delivered', label: '已发货' },
      { key: 'completed', label: '已完成' },
      { key: 'cancelled', label: '已取消' }
    ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.loadOrders()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 页面显示时刷新数据
    this.refreshOrders()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.refreshOrders()
    wx.stopPullDownRefresh()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    this.loadMoreOrders()
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: '我的订单',
      path: '/pages/orders/orders'
    }
  },

  /**
   * 加载订单列表
   */
  async loadOrders() {
    if (this.data.loading) return

    this.setData({ loading: true })

    try {
      const params = {
        pageNum: this.data.pageNum,
        pageSize: this.data.pageSize
      }

      if (this.data.currentTab !== 'all') {
        params.status = this.getStatusByTab(this.data.currentTab)
      }

      const result = await apiService.getMyOrders(params)
      const newOrders = result.list || []
      const orders = this.data.pageNum === 1 ? newOrders : [...this.data.orders, ...newOrders]

      this.setData({
        orders: orders,
        hasMore: newOrders.length === this.data.pageSize,
        loading: false
      })
    } catch (error) {
      this.setData({ loading: false })
      showError(error.message || '加载订单列表失败')
    }
  },

  /**
   * 根据标签页获取状态
   */
  getStatusByTab(tab) {
    const statusMap = {
      'pending': 1, // 待支付
      'paid': 2, // 已支付
      'delivered': 3, // 已发货
      'completed': 4, // 已完成
      'cancelled': 5 // 已取消
    }
    return statusMap[tab]
  },

  /**
   * 刷新订单列表
   */
  refreshOrders() {
    this.setData({
      orders: [],
      pageNum: 1,
      hasMore: true
    })
    this.loadOrders()
  },

  /**
   * 加载更多订单
   */
  loadMoreOrders() {
    if (!this.data.hasMore || this.data.loading) return

    this.setData({
      pageNum: this.data.pageNum + 1
    })
    this.loadOrders()
  },

  /**
   * 切换标签页
   */
  onTabChange(e) {
    const tab = e.currentTarget.dataset.tab
    this.setData({
      currentTab: tab
    })
    this.refreshOrders()
  },

  /**
   * 查看订单详情
   */
  onOrderTap(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/order-detail/order-detail?id=${id}`
    })
  },

  /**
   * 取消订单
   */
  async onCancelOrder(e) {
    e.stopPropagation() // 阻止冒泡
    const id = e.currentTarget.dataset.id

    try {
      wx.showModal({
        title: '取消订单',
        content: '确定要取消这个订单吗？',
        success: async (res) => {
          if (res.confirm) {
            await apiService.cancelOrder(id)
            showSuccess('订单取消成功')
            this.refreshOrders()
          }
        }
      })
    } catch (error) {
      showError(error.message || '取消订单失败')
    }
  },

  /**
   * 支付订单
   */
  async onPayOrder(e) {
    e.stopPropagation() // 阻止冒泡
    const id = e.currentTarget.dataset.id

    try {
      await apiService.payOrder(id)
      showSuccess('支付成功')
      this.refreshOrders()
    } catch (error) {
      showError(error.message || '支付失败')
    }
  },

  /**
   * 确认收货
   */
  async onConfirmOrder(e) {
    e.stopPropagation() // 阻止冒泡
    const id = e.currentTarget.dataset.id

    try {
      wx.showModal({
        title: '确认收货',
        content: '确认已收到商品吗？',
        success: async (res) => {
          if (res.confirm) {
            await apiService.confirmOrder(id)
            showSuccess('确认收货成功')
            this.refreshOrders()
          }
        }
      })
    } catch (error) {
      showError(error.message || '确认收货失败')
    }
  },

  /**
   * 申请退款
   */
  async onRefundOrder(e) {
    e.stopPropagation() // 阻止冒泡
    const id = e.currentTarget.dataset.id

    try {
      wx.showModal({
        title: '申请退款',
        content: '确定要申请退款吗？',
        success: async (res) => {
          if (res.confirm) {
            await apiService.refundOrder(id)
            showSuccess('退款申请已提交')
            this.refreshOrders()
          }
        }
      })
    } catch (error) {
      showError(error.message || '申请退款失败')
    }
  },

  /**
   * 获取状态文本
   */
  getStatusText(status) {
    const statusMap = {
      1: '待支付',
      2: '已支付',
      3: '已发货',
      4: '已完成',
      5: '已取消',
      6: '已退款'
    }
    return statusMap[status] || '未知状态'
  },

  /**
   * 获取状态样式类
   */
  getStatusClass(status) {
    const classMap = {
      1: 'status-pending',
      2: 'status-paid',
      3: 'status-delivered',
      4: 'status-completed',
      5: 'status-cancelled',
      6: 'status-refunded'
    }
    return classMap[status] || ''
  }
})